<template>
  <div class="user-center-container">
    <el-card class="user-card">
      <template #header>
        <div class="card-header">
          <span>个人中心</span>
        </div>
      </template>
      
      <div class="user-info">
        <el-row :gutter="20">
          <el-col :span="8" class="avatar-col">
            <div class="avatar-wrapper">
              <el-avatar :size="100" src="https://picsum.photos/1200/400?random=3" />
            </div>
          </el-col>
          
          <el-col :span="16">
            <div class="user-details">
              <el-descriptions :column="1" border>
                <el-descriptions-item label="学号/工号">{{ userInfo.id }}</el-descriptions-item>
                <el-descriptions-item label="用户名">{{ userInfo.username }}</el-descriptions-item>
                <el-descriptions-item label="用户昵称">{{ userInfo.nickname }}</el-descriptions-item>
                <el-descriptions-item label="用户姓名">{{ userInfo.realName }}</el-descriptions-item>
                <el-descriptions-item label="信用分">
                  <el-tag :type="getCreditTagType(userInfo.creditScore)">
                    {{ userInfo.creditScore }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="所属学校">{{ userInfo.school }}</el-descriptions-item>
                <el-descriptions-item label="邮箱">{{ userInfo.email }}</el-descriptions-item>
                <el-descriptions-item label="电话">{{ userInfo.phone }}</el-descriptions-item>
              </el-descriptions>
            </div>
          </el-col>
        </el-row>
        
        <div class="user-actions">
          <el-button type="primary" @click="openChangePasswordDialog">
            修改密码
          </el-button>
          <el-button type="success" @click="openBindSchoolDialog">
            绑定学校
          </el-button>
          <el-button type="success" @click="gotoManagement" v-if="userStore.getRoles.length>0">
            管理后台
          </el-button>
          <el-button type="info" @click="openEditProfileDialog">
            修改资料
          </el-button>
          <el-button type="warning" @click="returnStore">
            返回商店
          </el-button>
        </div>
      </div>
    </el-card>
    
    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="changePasswordDialogVisible"
      title="修改密码"
      width="500px"
      @close="resetPasswordForm"
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
      >
        <el-form-item label="原密码" prop="oldPassword">
          <el-input
            v-model="passwordForm.oldPassword"
            type="password"
            show-password
            placeholder="请输入原密码"
          />
        </el-form-item>
        
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            show-password
            placeholder="请输入新密码"
          />
        </el-form-item>
        
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            show-password
            placeholder="请再次输入新密码"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="changePasswordDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="passwordLoading"
          @click="handleChangePassword"
        >
          确认修改
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 绑定学校对话框 -->
    <el-dialog
      v-model="bindSchoolDialogVisible"
      title="绑定学校"
      width="500px"
    >
      <el-form
        ref="schoolFormRef"
        :model="schoolForm"
        :rules="schoolRules"
        label-width="100px"
      >
        <el-form-item label="选择学校" prop="school">
          <el-select
            v-model="schoolForm.school"
            placeholder="请选择学校"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="school in schoolOptions"
              :key="school.value"
              :label="school.label"
              :value="school.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="bindSchoolDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="schoolLoading"
          @click="handleBindSchool"
        >
          确认绑定
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 修改用户资料对话框 -->
    <el-dialog
      v-model="editProfileDialogVisible"
      title="修改用户资料"
      width="500px"
      @close="resetProfileForm"
    >
      <el-form
        ref="profileFormRef"
        :model="profileForm"
        :rules="profileRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="profileForm.username"
            placeholder="请输入用户名"
          />
        </el-form-item>
        
        <el-form-item label="昵称" prop="nickname">
          <el-input
            v-model="profileForm.nickname"
            placeholder="请输入昵称"
          />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="profileForm.email"
            placeholder="请输入邮箱"
          />
        </el-form-item>
        
        <el-form-item label="电话" prop="phone">
          <el-input
            v-model="profileForm.phone"
            placeholder="请输入电话号码"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="editProfileDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="profileLoading"
          @click="handleUpdateProfile"
        >
          确认修改
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'

// 响应式数据
const changePasswordDialogVisible = ref(false)
const bindSchoolDialogVisible = ref(false)
const editProfileDialogVisible = ref(false)
const passwordLoading = ref(false)
const schoolLoading = ref(false)
const profileLoading = ref(false)
const passwordFormRef = ref()
const schoolFormRef = ref()
const profileFormRef = ref()
const router = useRouter()
const userStore = useUserStore()

// 用户信息
const userInfo = reactive({
  id: '2021001001',
  username: 'zhangsan',
  nickname: '张小三',
  realName: '张三',
  creditScore: 95,
  school: '清华大学',
  email: 'zhangsan@tsinghua.edu.cn',
  phone: '138****8888'
})

// 修改密码表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 绑定学校表单
const schoolForm = reactive({
  school: ''
})

// 修改资料表单
const profileForm = reactive({
  username: '',
  nickname: '',
  email: '',
  phone: ''
})

// 学校选项（示例数据）
const schoolOptions = [
  { value: '清华大学', label: '清华大学' },
  { value: '北京大学', label: '北京大学' },
  { value: '复旦大学', label: '复旦大学' },
  { value: '上海交通大学', label: '上海交通大学' },
  { value: '浙江大学', label: '浙江大学' },
  { value: '中国科学技术大学', label: '中国科学技术大学' },
  { value: '南京大学', label: '南京大学' },
  { value: '华中科技大学', label: '华中科技大学' }
]

// 密码表单验证规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码至少6个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 学校表单验证规则
const schoolRules = {
  school: [
    { required: true, message: '请选择学校', trigger: 'change' }
  ]
}

// 资料表单验证规则
const profileRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, message: '用户名至少3个字符', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, message: '昵称至少2个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入电话号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
  ]
}

// 根据信用分获取标签类型
const getCreditTagType = (score) => {
  if (score >= 90) return 'success'
  if (score >= 70) return 'warning'
  return 'danger'
}

// 打开修改密码对话框
const openChangePasswordDialog = () => {
  changePasswordDialogVisible.value = true
}

// 打开绑定学校对话框
const openBindSchoolDialog = () => {
  schoolForm.school = userInfo.school
  bindSchoolDialogVisible.value = true
}

// 打开修改资料对话框
const openEditProfileDialog = () => {
  // 初始化表单数据
  profileForm.username = userInfo.username
  profileForm.nickname = userInfo.nickname
  profileForm.email = userInfo.email
  profileForm.phone = userInfo.phone
  editProfileDialogVisible.value = true
}

// 重置密码表单
const resetPasswordForm = () => {
  passwordFormRef.value?.resetFields()
}

// 重置资料表单
const resetProfileForm = () => {
  profileFormRef.value?.resetFields()
}

// 修改密码
const handleChangePassword = async () => {
  if (!passwordFormRef.value) return
  
  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      passwordLoading.value = true
      
      try {
        // 这里应该调用实际的修改密码API
        // await changePasswordApi(passwordForm)
        await new Promise(resolve => setTimeout(resolve, 1500))
        
        ElMessage.success('密码修改成功！')
        changePasswordDialogVisible.value = false
        resetPasswordForm()
      } catch (error) {
        ElMessage.error('密码修改失败，请稍后重试')
      } finally {
        passwordLoading.value = false
      }
    }
  })
}

// 绑定学校
const handleBindSchool = async () => {
  if (!schoolFormRef.value) return
  
  await schoolFormRef.value.validate(async (valid) => {
    if (valid) {
      schoolLoading.value = true
      
      try {
        // 这里应该调用实际的绑定学校API
        // await bindSchoolApi(schoolForm)
        await new Promise(resolve => setTimeout(resolve, 1500))
        
        // 更新用户信息
        userInfo.school = schoolForm.school
        
        ElMessage.success('学校绑定成功！')
        bindSchoolDialogVisible.value = false
      } catch (error) {
        ElMessage.error('学校绑定失败，请稍后重试')
      } finally {
        schoolLoading.value = false
      }
    }
  })
}

// 更新用户资料
const handleUpdateProfile = async () => {
  if (!profileFormRef.value) return
  
  await profileFormRef.value.validate(async (valid) => {
    if (valid) {
      profileLoading.value = true
      
      try {
        // 这里应该调用实际的更新用户资料API
        // await updateProfileApi(profileForm)
        await new Promise(resolve => setTimeout(resolve, 1500))
        
        // 更新用户信息
        userInfo.username = profileForm.username
        userInfo.nickname = profileForm.nickname
        userInfo.email = profileForm.email
        userInfo.phone = profileForm.phone
        
        ElMessage.success('用户资料更新成功！')
        editProfileDialogVisible.value = false
      } catch (error) {
        ElMessage.error('用户资料更新失败，请稍后重试')
      } finally {
        profileLoading.value = false
      }
    }
  })
}

const returnStore=()=>{
    router.push('/store')
}

const gotoManagement=()=>{
  if(userStore.getRoles) router.push('/management')
}

// 页面加载时获取用户信息
onMounted(() => {
  // 这里应该调用实际的获取用户信息API
  // fetchUserInfo()
})
</script>

<style scoped>
.user-center-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.user-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  text-align: center;
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.user-info {
  padding: 20px 0;
}

.avatar-col {
  display: flex;
  justify-content: center;
  align-items: flex-start;
}

.avatar-wrapper {
  padding-top: 10px;
}

.user-details {
  width: 100%;
}

.user-actions {
  margin-top: 30px;
  text-align: center;
}

.user-actions .el-button {
  margin: 0 10px;
}

:deep(.el-card__header) {
  padding: 20px 20px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-card__body) {
  padding: 30px;
}

:deep(.el-descriptions__label) {
  font-weight: 500;
  width: 120px !important;
}

@media (max-width: 768px) {
  .user-center-container {
    padding: 10px;
  }
  
  :deep(.el-descriptions__label) {
    width: 100px !important;
  }
  
  .user-actions .el-button {
    display: block;
    margin: 10px auto;
    width: 80%;
  }
}
</style>